package com.kaifamiao.month05.day18;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;

public class MyDataSource {

    public List<Connection> connections = Collections.synchronizedList(new LinkedList<Connection>());
    private static final int CAPACITY = 5;
    private int size;

    private static String url;
    private static String username;
    private static String password;

    static{
        File file = new File("E:\\git\\pictures\\kfm\\src\\main\\db.properties");
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            Properties prop = new Properties();
            prop.load(in);
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public MyDataSource() {
        this(CAPACITY);
    }

    public MyDataSource(int size) {
        this.size = size;
        init();
    }

    private void init() { // 初始化五个连接
        for (int i = 0; i < size; i++) {
            try {
                Connection conn = DriverManager.getConnection(url,username,password);
                connections.add(new MyConnection(connections,conn));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public Connection getConnection() { // 获取连接
        if (connections.size() != 0) {
            return connections.remove(0);
        }
        return null;
    }

}
